package com.topisv.tms.web.work;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.Servlets;
import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.lightShelf.LightShelf;
import com.topisv.tms.entity.lightShelf.LightShelfStock;
import com.topisv.tms.entity.lightShelf.LightShelfStockSku;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.entity.work.WorkTask;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.lightShelf.LightShelfService;
import com.topisv.tms.service.lightShelf.LightShelfStockService;
import com.topisv.tms.service.lightShelf.LightShelfStockSkuService;
import com.topisv.tms.service.work.WorkOrderService;
import com.topisv.tms.service.work.WorkTaskService;

/**
 * 灯光拣选任务_control
 * @author ch
 */
@Controller
@RequestMapping({ "/lampPickTask" })
public class LampPickTaskController {

	private static final Logger logger = LoggerFactory.getLogger(LampPickTaskController.class);

	@Autowired
	private WorkOrderService workOrderService;
	@Autowired
	private WorkTaskService workTaskService;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private LightShelfService lightShelfService;
	@Autowired
	private LightShelfStockService lightShelfStockService;
	@Autowired
	private LightShelfStockSkuService  lightShelfStockSkuService;
	
	/**
	 * 导向灯光拣选任务列表页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "v2_toLampPickTaskListPage")
	public String toLampPickTaskListPage(ServletRequest request,HttpServletResponse response,Model model){
		
		try {
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
	    
		    //查找我的灯光拣货任务
		    Map<String, Object> param_my=new HashMap<String, Object>();
		    param_my.put("lamperId", curUser.id);
		    param_my.put("pickModel", "lamp");
		    param_my.put("status", "myLampPick"); //任务状态( 1.创建任务 2.已分配拣货任务 3.已拣货 4. 已分配灯光拣选任务 5.已经灯光拣选 6.已分配包装任务 7.已包装 8.已分配发货任务 9.已发货 10.灯光拣选进行中.. 11.推车拣选进行中.. 12.拣货中...)
		    List<WorkTask> myLampPickTaskList=this.workTaskService.loadTaskByParam(param_my);
		    model.addAttribute("myLampPickTaskList",myLampPickTaskList);
		    
		    
		  //如果是paiu用户,初始化数据
			if("paiu".equals(curUser.userType)){
				//查询未分配的任务
	  			Map<String, Object> param = new HashMap<String, Object>();
	  			param.put("customerCodes", StringUtils.isBlank(curUser.customers)?"blank":curUser.customers);
				param.put("areagroups", StringUtils.isBlank(curUser.areagroups)?"blank":curUser.areagroups);
	  			param.put("pickModel", "lamp");
	  			param.put("status", "3"); //任务状态( 1.创建任务 2.已分配拣货任务  3.已拣货  4. 已分配灯光拣选任务  5.已经灯光拣选  6.已分配包装任务  7.已包装  8.已分配发货任务  9.已发货)
	  			List<WorkTask> untakedLampPickTaskList = this.workTaskService.loadTaskByParam(param);
	  			model.addAttribute("untakedLampPickTaskList", untakedLampPickTaskList);
			}
	    
		    
		    //如果是商家用户,初始化数据
			if("customer".equals(curUser.userType)){
				String customerCode=curUser.customerCode;
				model.addAttribute("customerCode", customerCode); 
				
				//初始化仓库数据
				List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser,customerCode);
				model.addAttribute("warehouseList", warehouseList);
				
				//查询未分配的任务
	  			Map<String, Object> param = new HashMap<String, Object>();
	  			param.put("customerCode", customerCode);
	  			param.put("pickModel", "lamp");
	  			param.put("status", "3"); //任务状态( 1.创建任务 2.已分配拣货任务  3.已拣货  4. 已分配灯光拣选任务  5.已经灯光拣选  6.已分配包装任务  7.已包装  8.已分配发货任务  9.已发货)
	  			List<WorkTask> untakedLampPickTaskList = this.workTaskService.loadTaskByParam(param);
	  			model.addAttribute("untakedLampPickTaskList", untakedLampPickTaskList);
	  			model.addAttribute("customerCode", customerCode);
			}
	    
		} catch (Exception e) {
			
		}
	    
		return "work/pick2th/lampPickTaskList";
	}
	
	/**
	 * 查询灯光拣选任务列表
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "v2_queryLampPickTaskList")
	public String queryLampPickTaskList(Model model, ServletRequest request, ServletResponse response) throws Exception {
		try {
			
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
		
			//查找我的灯光拣货任务
		    Map<String, Object> param_my=new HashMap<String, Object>();
		    param_my.put("lamperId", curUser.id);
		    param_my.put("pickModel", "lamp");
		    param_my.put("status", "myLampPick"); //任务状态( 1.创建任务 2.已分配拣货任务  3.已拣货  4. 已分配灯光拣选任务  5.已经灯光拣选  6.已分配包装任务  7.已包装  8.已领取发货任务  9.已发货  10.灯光拣选进行中..))
		    List<WorkTask> myLampPickTaskList=this.workTaskService.loadTaskByParam(param_my);
		    model.addAttribute("myLampPickTaskList",myLampPickTaskList);
	    
		    //查询未分配的任务
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			String warehouseCode=(String) param.get("warehouseCode");
			String customerCode=(String) param.get("customerCode");
			
			if(StringUtils.isBlank(customerCode)){
				String customerCodes=this.customersService.loadCustomerByAuthority(curUser.jobuuid);
				param.put("customerCodes", StringUtils.isBlank(customerCodes)?"blank":customerCodes);
			}else{
				param.put("customerCodes", customerCode);
			}
			
			if(StringUtils.isBlank(warehouseCode)){
				param.put("areagroups", StringUtils.isBlank(curUser.areagroups)?"blank":curUser.areagroups);
			}else{
				param.put("areagroups", warehouseCode);
			}
			
			param.put("pickModel", "lamp");
			param.put("status", "3"); //任务状态( 1.创建任务 2.已分配拣货任务  3.已拣货  4. 已分配灯光拣选任务  5.已经灯光拣选  6.已分配包装任务  7.已包装  8.已分配发货任务  9.已发货)
			List<WorkTask> untakedLampPickTaskList = this.workTaskService.loadTaskByParam(param);
			model.addAttribute("untakedLampPickTaskList", untakedLampPickTaskList);
			model.addAttribute("customerCode", customerCode);
			
			//初始化仓库数据
			List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser,customerCode);
			model.addAttribute("warehouseList", warehouseList);
		
		} catch (Exception e) {
			
			logger.error("error",e);
		}

		return "work/pick2th/lampPickTaskList";
	}
	
	/**
	 * 领取灯光拣选任务
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxTakeLampPickTask")
	@ResponseBody
	public String ajaxTakeLampPickTask(ServletRequest request,HttpServletResponse response) {
		try {	
			Long taskId=Long.valueOf(request.getParameter("taskId")+""); 
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			
			this.workTaskService.takeTask(taskId,curUser.id,"lampPick");
			return "true";
		} catch (Exception e) {
			logger.error("error",e);
			return "false";
		}
	}
	
	/**
	 * 导向灯光拣选任务页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "v2_toLampPickTaskPage/{taskId}", method = RequestMethod.GET)
	public String toLampPickTaskPage(@PathVariable("taskId") Long taskId, Model model) {
		try {

			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		    String customerCode=curUser.customerCode;
		    Customers customer=this.customersService.findByCustomerCode(customerCode);
		    model.addAttribute("customer", customer); 
		    model.addAttribute("curUser", curUser); 
		    
		    WorkTask  task=this.workTaskService.loadTaskById(taskId);
		    model.addAttribute("task", task);
		    
		    if(task.getStatus().equals("4")){ //任务未开始
		    	//查询空置灯光架
			    List<LightShelf> lightShelfList=this.lightShelfService.loadLightShelf(task.getWarehouseCode(),"free");
			    model.addAttribute("lightShelfList", lightShelfList);
		    }
		    else if(task.getStatus().equals("10")){   //任务进行中
		    	//查询任务关联的灯光架
			    LightShelf curLightShelf=this.lightShelfService.loadLightShelfById(task.getLightshelfId());
			    model.addAttribute("curLightShelf", curLightShelf);
			    
			    //查询未完成的信息
			    List<LightShelfStockSku> skuInfoList=this.lightShelfStockSkuService.loadByTaskAndUpstatus(task.getTaskCode(),"0");
			    model.addAttribute("skuInfoList", skuInfoList);
			    
			    //架位信息
			    List<LightShelfStock> curStockList=this.lightShelfStockService.loadStock(task.getLightshelfId());
			    model.addAttribute("curStockList", curStockList);
		    }
		    
		   
		    //查询任务订单
		    Map<String, Object> param=new HashMap<String, Object>();
		    param.put("taskCode", task.getTaskCode());
		    List<WorkOrder> orderList=this.workOrderService.loadOrder(param);
		    model.addAttribute("orderList", orderList);
		    
			
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		
		return "work/pick2th/lampPickTask";
	}
	
	
	/**
	 * 任务绑定灯光架
	 * @param shelfCode 架编码
	 * @param boxCode 箱编码
	 * @param jobuuid 
	 * @return
	 */
	@RequestMapping(value = "ajaxBindLightShelf")
	public void ajaxBindLightShelf(@RequestParam(value = "shelfCode") String shelfCode,@RequestParam(value = "taskCode") String taskCode,HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			
			WorkTask task=this.workTaskService.loadTaskByCode(taskCode);
			LightShelf shelf=this.lightShelfService.loadLightShelfByShelfCode(shelfCode);
			
			//任务绑定灯光架
			Map<String, String> map=this.lightShelfService.bindLightShelf(shelfCode,task.getBoxCode(),curUser.jobuuid); 
			String msg=map.get("msg");
			if("busy".equals(msg)){
				json.put("status", "4");
				json.put("content", "灯光架已被占用");
			}
			else if("less".equals(msg)){
				json.put("status", "3");
				json.put("content", "灯光架位数不够！");
			}
			else if("continue".equals(msg)){
				json.put("status", "2");
				json.put("content", (String)map.get("taskCode"));
			}
			else if("success".equals(msg)){
				json.put("status", "1");
				
				//灯光架
				LightShelf lightShelf=this.lightShelfService.loadLightShelfById(shelf.getId());
				json.put("lightShelf", lightShelf);
				
				//灯光架库位信息
				List<LightShelfStock> stockList=this.lightShelfStockService.loadStock(shelf.getId());
				json.put("stockList", stockList);
				
				//订单信息
				Map<String, Object> param=new HashMap<String, Object>();
			    param.put("taskCode",taskCode);
			    param.put("billStatus", "0");
			    List<WorkOrder> orderList=this.workOrderService.loadOrder(param);
			    json.put("orderList", orderList);
				
			}
			
		} catch (Exception e) {
			
			logger.error("error",e);
			json.put("status", "0");
			json.put("content", "服务器异常");
		}
		out.print(json.toString());
	}
	
	/**
	 * ajax商品上架
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxSetGoods")
	public String ajaxSetGoods(ServletRequest request,HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			
			String shelfCode=request.getParameter("shelfCode");
			Long taskId=Long.valueOf(request.getParameter("taskId"));
			WorkTask task=this.workTaskService.loadTaskById(taskId);
			String sku=request.getParameter("sku");
			
			//上架
			Map<String,String> result=this.lightShelfService.setGoods(shelfCode,sku,task.getTaskCode());
			
			json.put("msg", result.get("msg"));  //返回信息
			json.put("stockCode", result.get("stockCode")); //返回灯光架位
			json.put("isFinished", result.get("isFinished")); //返回是否完全部上架
			
			out.print(json);
			
		} catch (Exception e) {
			
			logger.error("error",e);
			json.put("msg", "error");
			out.print(json);
		}
		return null;
	}
	
	
	
	
	/**
	 * ajax完成任务
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxCompleteLampPickTask")
	public String ajaxCompleteLampPickTask(ServletRequest request,HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			String taskCode=request.getParameter("taskCode");
			
			//完成任务
			String msg=this.lightShelfService.completeLampPickTask(taskCode);
			
			
			json.put("msg", msg);
			out.print(json);
			
		} catch (Exception e) {
			
			logger.error("error",e);
			json.put("msg", "error");
			out.print(json);
		}
		return null;
	}
	
	
	
}